/*
 * @lc app=leetcode id=725 lang=cpp
 *
 * [725] Split Linked List in Parts
 */
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    int getLen(ListNode *node) {
        int len = 0;
        while(node) {
            node = node->next;
            len++;
        }
        return len;
    }
    vector<ListNode*> splitListToParts(ListNode* root, int k) {
        int len = getLen(root);
        if (k < 1) {
            return {NULL};
        }
        if (len < 1) {
            return vector<ListNode *>(k, NULL);
        }

        int persize = len/k;
        int more=  len%k;
        vector<int> vSize(k, persize);
        vector<ListNode *> v(k, NULL);

        for (int i=0; i<more; i++) {
            vSize[i]++;
        }

        int i = 0;
        ListNode *node = root;
        ListNode *slice = node;
        for (auto l : vSize) {
            v[i++] = slice;
            ListNode *n = slice;
            while(n && l > 0) {
                l--;
                if (l == 0) {
                    slice = n->next;
                    n->next = NULL;
                }
                n = n->next;
            }
        }
        return v;
    }
};

